package com.cmw.controller.global.configuration;

import java.io.File;
import java.nio.charset.Charset;

import com.cmw.core.util.StringHandler;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Remark tomcat 自定义配置
 * @Author 程明卫
 * @Date 2017-05-18 17:56
 */
@Configuration
public class TomcatConfig {

    /**
     * HTTP端口
     */
    @Value("${server.port}")
    private Integer server_port;

    /**
     * SSL端口
     */
    @Value("${server.ssl.port}")
    private Integer server_ssl_port;
    /**
     * 是否启用 SSL [true:启用,false:不启用]
     */
    @Value("${server.ssl.enabled}")
    private Boolean server_ssl_enabled;
    /**
     * KEY别名
     */
    @Value("${server.ssl.keyAlias}")
    private String server_ssl_keyAlias;
    /**
     * KEY文件密码
     */
    @Value("${server.ssl.keyPassword}")
    private String server_ssl_keyPassword;
    /**
     *  SLL KEY证书文件路径
     */
    @Value("${server.ssl.keyStore}")
    private String server_ssl_keyStore;
    /**
     *最大连接数 , 生产环境可调成：1到2000##
     */
    @Value("${server.tomcat.maxConnections}")
    private Integer server_tomcat_maxConnections;
    /**
     *最大线程数, 生产环境可调成：1到2000##
     */
    @Value("${server.tomcat.maxThreads}")
    private Integer server_tomcat_maxThreads;
    /**
     *   ##超时时间,生产环境可调成：30秒##
     */
    @Value("${server.tomcat.timeout}")
    private Integer server_tomcat_timeout;
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.setUriEncoding(Charset.forName("UTF-8"));
        // SSL 证书及端口配置
        if(null == server_ssl_enabled || !server_ssl_enabled.booleanValue()){
            tomcat.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
        }else{
            tomcat.addAdditionalTomcatConnectors(createSslConnector());
        }
        return tomcat;
    }

    /**
     * Tomcat https SSL证书及端口配置
     * @return
     */
    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        try {
            File truststore = new File(server_ssl_keyStore);
            connector.setScheme("https");
            protocol.setSSLEnabled(server_ssl_enabled);
            connector.setSecure(true);
            if(StringHandler.isValidIntegerNull(server_ssl_port)){//如果有配置 https 端口就使用 https 端口,否则就使用http端口
                connector.setPort(server_ssl_port);
            }else{
                connector.setPort(server_port);
            }

            protocol.setKeystoreFile(truststore.getAbsolutePath());
            protocol.setKeystorePass(server_ssl_keyPassword);
            protocol.setKeyAlias(server_ssl_keyAlias);
            setProps(protocol);
            return connector;
        } catch (Exception ex) {
            throw new IllegalStateException("cant access keystore: [" + server_ssl_keyStore + "]  ", ex);
        }
    }

    /**
     * Tomcat 自定义优化
     */
    class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer
    {
        public void customize(Connector connector)
        {
            Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
            setProps(protocol);
        }
    }

    /**
     * 设置性能参数
     * @param protocol
     */
    private void setProps(Http11NioProtocol protocol) {
        //设置最大连接数
       if(null != server_tomcat_maxConnections && server_tomcat_maxConnections.intValue() > 0){
           protocol.setMaxConnections(server_tomcat_maxConnections);
       }
       //设置最大线程数
       if(null != server_tomcat_maxThreads && server_tomcat_maxThreads.intValue() > 0){
            protocol.setMaxThreads(server_tomcat_maxThreads);
       }
       //设置超时时间
        if(null != server_tomcat_timeout && server_tomcat_timeout.intValue() > 0){
            protocol.setConnectionTimeout(server_tomcat_timeout);
        }

    }

//    /**
//     * Tomcat https SSL证书及端口配置
//     * @return
//     */
//    private Connector createSslConnector() {
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
//        try {
//            File truststore = new File("/Users/liaokailin/software/ca1/keystore");
//            connector.setScheme("https");
//            protocol.setSSLEnabled(true);
//            connector.setSecure(true);
//            connector.setPort(8443);
//            protocol.setKeystoreFile(truststore.getAbsolutePath());
//            protocol.setKeystorePass("123456");
//            protocol.setKeyAlias("springboot");
//            return connector;
//        } catch (Exception ex) {
//            throw new IllegalStateException("cant access keystore: [" + "keystore" + "]  ", ex);
//        }
//    }
}
